package org.healthy.serviceimpl;

import org.healthy.base.BaseService;
import org.healthy.base.constant.RedisKeyConst;
import org.healthy.dao.PaperMapper;
import org.healthy.model.page.Pagination;
import org.healthy.model.user.Paper;
import org.healthy.service.IPaperService;
import org.healthy.utils.JsonUtil;
import org.healthy.utils.pub.tool.StringUtils;
import org.healthy.utils.redis.CommRedisOperator;
import org.healthy.utils.redis.RedisOperator;
import org.springframework.stereotype.Service;
import sun.jvm.hotspot.debugger.Page;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by qingshengzheng on 17/10/11.
 */
@Service("userService")
public class PaperServiceImpl extends BaseService implements IPaperService {
    @Resource
    public PaperMapper paperMapper;

    public CommRedisOperator redisoper;

    public Paper getPaperByid(String id) {
        Paper paper = null;
        String key = redisoper.format(RedisKeyConst.CACHE_PAPER, id);
        String json = redisoper.get(key, 0);
        if (!StringUtils.isNull(json)) {
            paper = (Paper) JsonUtil.fromJson(json, Paper.class);

        } else {
            paper = paperMapper.getPaper(id);
        }

        return paper;

    }

    /**
     * 用户收藏试卷
     *
     * @param uid
     * @param pid
     */
    public void collectPaper(Long uid, String pid) {
        paperMapper.addPaperRel(uid, pid);
        String key = redisoper.format(RedisKeyConst.CACHE_USER_COLLECT_PAPERS, uid);
        redisoper.lpush(key, pid, 0);
    }

    /**
     * 获取收藏的试卷
     *
     * @param uid
     * @param page
     * @return
     */
    public List<Paper> getCollectPaper(Long uid, Pagination<Paper> page) {
        List<Paper> papers = new ArrayList<Paper>();
        String key = redisoper.format(RedisKeyConst.CACHE_USER_COLLECT_PAPERS, uid);
        long start = page.getStart();
        long end = page.getEnd();
        List<String> ids = redisoper.rrange(key, page.getStart(), page.getEnd(), 0);
        for (String id : ids) {
            papers.add(getPaperByid(id));
        }
        return papers;
    }

    public List<Paper> searchPapersByKeywords(String keyword) {
        return null;
    }

    public List<Paper> searchPaper(Paper paper) {
        return null;
    }


    /**
     * 获取试卷标题
     *
     * @param pid
     * @return
     */
    public String getPaperTitle(String pid) {
        String title = paperMapper.getPaperTitle(pid);
        return title;
    }

    public List<Paper> getRmdPapers(Long uid, Pagination<Paper> page) {
        List<Paper> papers = new ArrayList<Paper>();
        String key = redisoper.format(RedisKeyConst.CAHCE_RMD_PAPER, uid);
        List<String> ids = redisoper.rrange(key, page.getStart(), page.getEnd(), 0);
        for (String id : ids) {
            papers.add(getPaperByid(id));
        }
        return papers;
    }
}
